package com.qsmx.qingqiuticket.app.util;

import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.usb.UsbDevice;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.OptIn;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.video.FileOutputOptions;
import androidx.camera.video.PendingRecording;
import androidx.camera.video.Quality;
import androidx.camera.video.QualitySelector;
import androidx.camera.video.Recorder;
import androidx.camera.video.Recording;
import androidx.camera.video.VideoCapture;
import androidx.camera.video.VideoRecordEvent;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.common.util.concurrent.ListenableFuture;
import com.herohan.uvcapp.CameraHelper;
import com.herohan.uvcapp.ICameraHelper;
import com.qsmx.core.util.dimen.DimenUtil;
import com.qsmx.core.util.log.AtmosLogger;
import com.qsmx.qingqiuticket.app.R;
import com.qsmx.qingqiuticket.app.delegate.back.camera.adapter.ImgAdapter;
import com.qsmx.qingqiuticket.app.view.diooto.Diooto;
import com.qsmx.qingqiuticket.app.view.diooto.config.DiootoConfig;
import com.serenegiant.usb.Size;
import com.serenegiant.utils.UriHelper;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import me.panpf.sketch.SketchImageView;

public class CameraManager {
//    private static ICameraHelper mCameraHelper;
//    private static ICameraHelper.StateCallback mStateListener;

    private static ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
    private static ProcessCameraProvider cameraProvider;
    private static CameraSelector cameraSelector; // 使用后置摄像头

    private static ImageCapture imageCapture;
    private static VideoCapture<Recorder> videoCapture;
    private static Recording videoRecording;
    private static int mPreviewRotation = 0;

    public static void initCamera(Context context) {
        //UVC摄像头状态回调
//        mStateListener = new ICameraHelper.StateCallback() {
//            //插入UVC设备
//            @Override
//            public void onAttach(UsbDevice device) {
//                //设置为当前设备（如果没有权限，会显示授权对话框）
//                mCameraHelper.selectDevice(device);
//            }
//
//            //打开UVC设备成功（也就是已经获取到UVC设备的权限）
//            @Override
//            public void onDeviceOpen(UsbDevice device, boolean isFirstOpen) {
//                //打开UVC摄像头
//                mCameraHelper.openCamera();
//            }
//
//            //打开摄像头成功
//            @Override
//            public void onCameraOpen(UsbDevice device) {
//                //开始预览
//            }
//
//            //关闭摄像头成功
//            @Override
//            public void onCameraClose(UsbDevice device) {
//            }
//
//            //关闭UVC设备成功
//            @Override
//            public void onDeviceClose(UsbDevice device) {
//            }
//
//            //断开UVC设备
//            @Override
//            public void onDetach(UsbDevice device) {
//            }
//
//            //用户没有授予访问UVC设备的权限
//            @Override
//            public void onCancel(UsbDevice device) {
//            }
//
//        };
//
//        mCameraHelper = new CameraHelper();
//        //设置UVC摄像头状态回调
//        mCameraHelper.setStateCallback(mStateListener);

        cameraProviderFuture = ProcessCameraProvider.getInstance(context);
        cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA; // 使用后置摄像头
        imageCapture = new androidx.camera.core.ImageCapture.Builder()
                .setCaptureMode(androidx.camera.core.ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
                .build();
    }

    public static void takeVideo(Context context, String orderNo, LifecycleOwner lifecycleOwner) {
        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                bindVideoCapture(cameraProvider, context, orderNo, lifecycleOwner);
            } catch (ExecutionException | InterruptedException e) {
            }
        }, ContextCompat.getMainExecutor(context));
    }

    // 绑定视频捕获功能
    @OptIn(markerClass = androidx.camera.video.ExperimentalHighSpeedVideo.class)
    public static void bindVideoCapture(@NonNull ProcessCameraProvider cameraProvider, Context context, String orderNo, LifecycleOwner lifecycleOwner) {
        // 配置 Recorder 和 VideoCapture
        Recorder recorder = new Recorder.Builder()
                .setQualitySelector(QualitySelector.from(Quality.HD))
                .build();
        videoCapture = VideoCapture.withOutput(recorder);
        CameraSelector cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;

        try {
            // 取消之前的绑定并重新绑定
            cameraProvider.unbindAll();
            cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, videoCapture);
            startRecording(context, orderNo);  // 自动开始录制视频
        } catch (Exception e) {
        }
    }

    // 开始录制视频
    private static void startRecording(Context context, String orderNo) {
        File outputDir = new File(SaveHelper.getSaveVideoParentPath(orderNo));
        ;  // 获取文件保存路径
        File videoFile = new File(outputDir, "video_capture_" + System.currentTimeMillis() + ".mp4");

        // 设置文件输出选项
        FileOutputOptions fileOutputOptions = new FileOutputOptions.Builder(videoFile).build();

        // 创建录制会话
        PendingRecording pendingRecording = videoCapture.getOutput().prepareRecording(context, fileOutputOptions);

//        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
//            pendingRecording.withAudioEnabled();  // 启用音频录制
//        }

        // 开始录制
        videoRecording = pendingRecording.start(ContextCompat.getMainExecutor(context), videoRecordEvent -> {
            if (videoRecordEvent instanceof VideoRecordEvent.Start) {
            } else if (videoRecordEvent instanceof VideoRecordEvent.Finalize) {
                // 录制完成后处理
                VideoRecordEvent.Finalize finalizeEvent = (VideoRecordEvent.Finalize) videoRecordEvent;
                if (!finalizeEvent.hasError()) {
                    AtmosLogger.d("VideoCaptureActivity", "Video saved successfully: " + videoFile.getAbsolutePath());
                } else {
                    AtmosLogger.e("VideoCaptureActivity", "Error saving video: " + finalizeEvent.getError());
                }
            }
        });

        // 可选：指定录制时间限制，例如 10 秒后自动停止
//        postDelayed(this::stopRecording, 10000); // 10 秒后停止录制
    }

    // 停止录制视频
    public static void stopRecording() {
        if (videoRecording != null) {
            videoRecording.stop();
            videoRecording = null;
        }
    }

    public static void takePicture(Context context, LifecycleOwner lifecycleOwner, String orderNo) {
//        try {
//            File file = new File(SaveHelper.getSavePhotoPath(orderNo));
//            ImageCapture.OutputFileOptions options =
//                    new ImageCapture.OutputFileOptions.Builder(file).build();
//            mCameraHelper.takePicture(options, new ImageCapture.OnImageCaptureCallback() {
//            @Override
//                public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
//                }
//
//                @Override
//                public void onError(int imageCaptureError, @NonNull String message, @Nullable Throwable cause) {
//                }
//            });
//        } catch (Exception e) {
//        }

        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                cameraProvider.unbindAll();
                cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, imageCapture);

                // 设置输出文件选项
                File photoFile = new File(SaveHelper.getSavePhotoPath(orderNo));
                ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions.Builder(photoFile).build();

                // 拍照并保存
                imageCapture.takePicture(outputFileOptions, ContextCompat.getMainExecutor(context), new androidx.camera.core.ImageCapture.OnImageSavedCallback() {
                    @Override
                    public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                        // 照片保存成功，可以在这里处理保存的文件，例如显示一个Toast消息或者将其显示在ImageView中
//                        Uri photoUri = Uri.fromFile(outputFileResults.getSavedUri());
                        System.out.println("拍照成功，保存路径：" + photoFile.getAbsolutePath());
                    }

                    @Override
                    public void onError(@NonNull ImageCaptureException exception) {
                        // 处理错误，例如显示一个Toast消息
                    }
                });
            } catch (ExecutionException | InterruptedException e) {
                e.printStackTrace();
            }
        }, ContextCompat.getMainExecutor(context));

    }

    //获取订单照片列表
    public static List<String> getPictures(String orderNo) {
        List<String> filesPath = new ArrayList<>();
        File directory = new File(SaveHelper.getSavePhotoParentPath(orderNo));
        if (directory.exists()) {
            File[] files = directory.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.toLowerCase().endsWith(".png")
                            || name.toLowerCase().endsWith(".jpg")
                            || name.toLowerCase().endsWith(".jpeg"); // 可以根据需要添加更多格式
                }
            });

            if (files != null) {
                // 打开第一个图片文件
                for (File file : files) {
                    filesPath.add(file.getAbsolutePath());
                }
            }
            return filesPath;
        } else {
            return new ArrayList<>();
        }
    }

    //获取订单照片列表
    public static List<String> getVideos(String orderNo) {
        List<String> filesPath = new ArrayList<>();
        File directory = new File(SaveHelper.getSavePhotoParentPath(orderNo));
        if (directory.exists()) {
            File[] files = directory.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.toLowerCase().endsWith(".mp4"); // 可以根据需要添加更多格式
                }
            });

            if (files != null) {
                // 打开第一个图片文件
                for (File file : files) {
                    filesPath.add(file.getAbsolutePath());
                }
            }
            return filesPath;
        } else {
            return new ArrayList<>();
        }
    }

    public static void showOpenImgDialog(Context context, List<String> imgList) {
        Dialog imgDialog = new Dialog(context, com.qsmx.core.R.style.dialog);
        imgDialog.setCancelable(false);
        imgDialog.show();
        Window window = imgDialog.getWindow();
        window.setContentView(R.layout.dialog_show_img);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);

        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        AppCompatTextView tvCancel = window.findViewById(R.id.tv_back_now);

        RecyclerView rlvImg = window.findViewById(R.id.rlv_pic);
        ImgAdapter imgAdapter = new ImgAdapter(context);
        LinearLayoutManager manager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
        rlvImg.setLayoutManager(manager);
        rlvImg.setAdapter(imgAdapter);
        imgAdapter.setImgs(imgList);

        imgAdapter.setonItemClickListener(new ImgAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                String[] array = (String[]) imgList.toArray(new String[imgList.size()]);
                View[] views = new View[imgList.size()];

                Diooto diooto = new Diooto(context)
                        .indicatorVisibility(View.VISIBLE)
                        .urls(array)
                        .type(DiootoConfig.VIDEO)
                        .immersive(true)
                        .position(position, 0)
                        .views(views)
                        .loadPhotoBeforeShowBigImage(new Diooto.OnLoadPhotoBeforeShowBigImageListener() {
                            @Override
                            public void loadView(SketchImageView sketchImageView, int position) {
                                sketchImageView.displayImage(imgList.get(position));
                                sketchImageView.setOnLongClickListener(new View.OnLongClickListener() {
                                    @Override
                                    public boolean onLongClick(View v) {
                                        return false;
                                    }
                                });
                            }
                        }).start();
            }
        });


        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imgDialog.dismiss();
            }
        });
    }
}
